package com.study.controller;

import com.study.dao.UserDao;
import com.study.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    private UserDao userDao = new UserDao();

    @PostMapping("login")
    public String login(String name, String password, Model model, HttpSession session) {
        User user = userDao.login(name, password);
        if (null == user) {
            model.addAttribute("error", "用户名或者密码错误");
            return "error";
        }
        session.setAttribute("userId", user.getId());
        return "home";
    }

    @PostMapping("register")
    public String register(String name, String password, Model model) {
        User user = userDao.selectByName(name);
        if (null != user) {
            model.addAttribute("error", "用户名已经存在");
            return "error";
        }
        userDao.register(name, password);
        return "index";
    }

    @RequestMapping("userDel")
    public String userDel(Integer userId,Model model){
        userDao.del(userId);
        model.addAttribute("error", "删除成功");
        return "error";
    }
}
